<?php
namespace Swostar\Supper;

class Inotify
{
    private $fd;
    private $watchPath;
    private $watchMask;
    private $watchHandler;
    private $doing = false;

    // 需要检测的文件后缀
    private $fileTypes = [
        '.php' => true
    ];

    private $wdPath = [];
    private $pathWd = [];


    public function __construct($watchPath, callable $watchHandler, $watchMask = IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVE)
    {
        if (!extension_loaded('inotify')) {
            exit('inotify 扩展未加载');
        }
        $this->fd = inotify_init();
        $this->watchPath = $watchPath;
        $this->watchMask = $watchMask;
        $this->watchHandler = $watchHandler;
        $this->watch();

    }


    public function watch() 
    {
        $this->_watch($this->watchPath);
    }

    protected function _watch($path)
    {
        $wd = inotify_add_watch($this->fd, $path, $this->watchMask);
        if ($wd === false) {
            return false;
        }

        $this->bind($wd, $path);

        if (is_dir($path)) {
            $wd = inotify_add_watch($this->fd, $path, $this->watchMask);
            if ($wd === false) {
                return false;
            }
            $this->bind($wd, $path);

            // 列出 $path中 目录中的文件和目录：
            $files = scandir($path);
            foreach ($files as $file) {
                if ($file === '.' || $file === '..') {
                    continue;
                }

                $file = $path . DS . $file;
                if (is_dir($file)) {
                    $this->_watch($file);
                }
            }
        }

        return true;
    }

    protected function bind($wd, $path) 
    {
        $this->wdPath[$path] = $wd;
        $this->pathWd[$wd] = $path;
    }





}

